/**
 * Baijiahulian.com Inc. Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.baijia.web.controller.deprecated;

import com.baijia.authentication.handler.exception.AuthenticationException;
import com.baijia.authentication.handler.exception.UrlMessageException;
import com.baijia.authentication.principal.Credentials;
import com.baijia.authentication.principal.SimpleWebApplicationServiceImpl;
import com.baijia.util.MobileLoginUtil;
import com.baijia.util.RestUtils;
import com.baijia.web.controller.AbstractAuthorizeController;
import com.baijia.web.dto.response.MobileResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @title MobileAuthorizeController
 * @desc 给H5和native使用的登录入口
 * @author macrohuang
 * @date Jan 22, 2016
 * @version 1.0
 */
@Controller
public class RestAuthorizeOldController extends AbstractAuthorizeController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // private static final String TEST_SIGN = "test123";

    @Value("${rest.appId}")
    private String appId;
    @Value("${rest.appKey}")
    private String appKey;
    @Value("${rest.appServiceUrl}")
    private String baseUrl;

    private final int MAX_RETRIES = 3;
    private final int BLOCK_IN_SECONDS = 3600;

    @RequestMapping(value = "/rest/login.do", method = RequestMethod.POST)
    @ResponseBody
    public MobileResponse<String> login(HttpServletRequest request) {
        MobileResponse<String> response = new MobileResponse<>();

        // APPID 不能为空
        String appId = request.getParameter(APPID);
        if (StringUtils.isBlank(appId)) {
            logger.info("appid is null");
            response.fail().msg("AppId is null");
            return response;
        }

        // 生成credentials
        Credentials credentials = generateCredentials(request);
        if (credentials == null) {
            response.fail().msg("Account not support!");
            return response;
        } else if (StringUtils.isBlank(credentials.getUsername())) {
            credentials = null;
            response.fail().msg("Username can't be null.");
            return response;
        }

        // 生成TGT，存储redis，生成ST，跳转orginalUrl
        SimpleWebApplicationServiceImpl service = null;
        try {
            service = SimpleWebApplicationServiceImpl.createServiceFrom(request, httpClient);
            logger.info("service:" + service);
            String TGTID = cookieRetrievingCookieGenerator.retrieveCookieValue(request);
            String ST = null;
            if (StringUtils.isBlank(TGTID)) {
                // create
                TGTID = centralAuthenticationService.createTicketGrantingTicket(credentials);
                ST = centralAuthenticationService.grantServiceTicket(TGTID, service);
            } else {
                // from cookie
                ST = centralAuthenticationService.grantServiceTicket(TGTID, service, credentials);
            }
            response.data(ST);
        } catch (UrlMessageException e) {
            logger.info("login fail! credentials:{},msg:{}", credentials, e.getMessage());
            response.fail().msg(e.getMessage());
        } catch (AuthenticationException e) {
            logger.error("createTicketGrantingTicket error!credentials:" + credentials, e);
            response.fail().msg(e.getMessage());
        } catch (Exception e) {
            logger.error("System error!", e);
            response.fail().msg("System error!");
        }
        return response;
    }

    @RequestMapping(value = { "/rest/sendPasscode.do" })
    @ResponseBody
    public MobileResponse<String> sendPasscode(@RequestParam(value = "accountMobile") String mobile) {
        MobileResponse<String> response = new MobileResponse<>();
        // 使用严格模式，即当前用户如果被禁止登录了，第一次尝试都把禁止登录时间延长一倍
        if (MobileLoginUtil.isUserBlock(mobile)) {
            response.fail().msg("用户当前被禁止登录，请1小时后再试！");
            MobileLoginUtil.blockUser(mobile, BLOCK_IN_SECONDS);
        } else if (!MobileLoginUtil.canSendPasscode(mobile)) {
            response.fail().msg("登录过于频繁，请1分钟后再试！");
            MobileLoginUtil.touchSendSeperate(mobile);
        } else if (MobileLoginUtil.getUserRetries(mobile) > MAX_RETRIES) {
            response.fail().msg("超过最大重试次数，用户将被禁止登录1小时！");
            MobileLoginUtil.blockUser(mobile, BLOCK_IN_SECONDS);
        } else {
            Map<String, String> result = MobileLoginUtil.sendPasscode(mobile, 0);
            if (result != null) {
                response.setCode(Integer.valueOf(result.get("result_code")));
                response.setMsg(result.get("result_msg"));
            } else {
                response.fail().msg("验证码发送失败，请稍后重试！");
            }
        }
        return response;
    }

    @RequestMapping("/v1/rest/sendSms.json")
    @ResponseBody
    public MobileResponse<String> sendSms(@RequestParam(value = "mobile") String mobile) {
        return sendPasscode(mobile);
    }

    @RequestMapping("/v1/rest/validateSms.json")
    @ResponseBody
    public MobileResponse<String> validatePasscode(@RequestParam(value = "mobile") String mobile,
        @RequestParam(value = "code") String code) {
        MobileResponse<String> response = new MobileResponse<>();
        if (MobileLoginUtil.validPasscode(mobile, code)) {
            return response;
        } else {
            response.fail().msg("验证码不一致！");
            return response;
        }
    }

    @RequestMapping("/rest/logout.do")
    @ResponseBody
    public MobileResponse<String> logout(HttpServletRequest request, HttpServletResponse response) {
        String ticketGrantingTicketId = cookieRetrievingCookieGenerator.retrieveCookieValue(request);
        logger.info("logout TGT:{}", ticketGrantingTicketId);

        // try {
        // if (ticketGrantingTicketId != null) {
        // this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
        // logger.info("logout destroyTicketGrantingTicket:{}", ticketGrantingTicketId);
        // }
        // } catch (Exception e) {
        // logger.error("logout error", e);
        // } finally {
        // this.cookieRetrievingCookieGenerator.removeCookie(response);
        // // 删除共享sessionid，使得师资、客服跳转过来的登录能够退出
        // dessionCookieCleaner.removeCookie(response);
        // logger.info("logout removeCookie:{}", ticketGrantingTicketId);
        // }
        handleLogout(ticketGrantingTicketId, request, response);
        return new MobileResponse<String>().msg("退出成功！");
    }

    @PostConstruct
    protected void init() {
        RestUtils.init(appId, appKey, baseUrl);
    }
}
